import React, { useState, useEffect } from 'react';

const GrammarQuestion = ({ question, onAnswer, onNext }) => {
  const [selectedOption, setSelectedOption] = useState(null);
  const [isCorrect, setIsCorrect] = useState(null);
  const [showExplanation, setShowExplanation] = useState(false);
  const [message, setMessage] = useState('');
  const [shuffledOptions, setShuffledOptions] = useState([]);

  // 选项随机化
  const shuffleOptions = (options) => {
    const shuffled = [...options];
    for (let i = shuffled.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
    }
    return shuffled;
  };

  // 当题目改变时，重新随机化选项并重置状态
  useEffect(() => {
    setShuffledOptions(shuffleOptions(question.options));
    setSelectedOption(null);
    setIsCorrect(null);
    setShowExplanation(false);
    setMessage('');
  }, [question.id]);

  const handleOptionSelect = (optionId) => {
    if (isCorrect !== null) return; // 已经回答过了
    setSelectedOption(optionId);
  };

  const checkAnswer = () => {
    if (selectedOption === null) {
      setMessage('请选择一个选项');
      return;
    }

    const selectedOptionData = shuffledOptions.find(opt => opt.id === selectedOption);
    const isAnswerCorrect = selectedOptionData.isCorrect;

    setIsCorrect(isAnswerCorrect);

    if (isAnswerCorrect) {
      setMessage('正确！🎉');
      onAnswer(true, selectedOption, false);
    } else {
      setMessage('不正确，请重试。');
      onAnswer(false, selectedOption, false);
    }
  };

  const resetQuestion = () => {
    setSelectedOption(null);
    setIsCorrect(null);
    setShowExplanation(false);
    setMessage('');
    setShuffledOptions(shuffleOptions(question.options));
  };

  const getOptionStyle = (optionId) => {
    if (selectedOption !== optionId) {
      return {
        padding: '15px',
        margin: '10px 0',
        border: '2px solid #e1e5e9',
        borderRadius: '10px',
        cursor: 'pointer',
        transition: 'all 0.3s ease',
        backgroundColor: '#fff'
      };
    }

    if (isCorrect === null) {
      return {
        padding: '15px',
        margin: '10px 0',
        border: '2px solid #667eea',
        borderRadius: '10px',
        cursor: 'pointer',
        transition: 'all 0.3s ease',
        backgroundColor: '#f0f4ff'
      };
    }

    const optionData = shuffledOptions.find(opt => opt.id === optionId);
    if (optionData.isCorrect) {
      return {
        padding: '15px',
        margin: '10px 0',
        border: '2px solid #28a745',
        borderRadius: '10px',
        cursor: 'pointer',
        transition: 'all 0.3s ease',
        backgroundColor: '#d4edda',
        color: '#155724'
      };
    } else {
      return {
        padding: '15px',
        margin: '10px 0',
        border: '2px solid #dc3545',
        borderRadius: '10px',
        cursor: 'pointer',
        transition: 'all 0.3s ease',
        backgroundColor: '#f8d7da',
        color: '#721c24'
      };
    }
  };

  return (
    <div className="card">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
        <h2>N4-N2语法考察</h2>
        <span style={{ 
          padding: '5px 15px', 
          borderRadius: '20px', 
          backgroundColor: '#667eea', 
          color: 'white',
          fontSize: '14px',
          fontWeight: 'bold'
        }}>
          {question.level}
        </span>
      </div>
      
      <div className="japanese-text" style={{ fontSize: '20px', marginBottom: '30px' }}>
        {question.question}
      </div>

      <div style={{ marginBottom: '30px' }}>
        {shuffledOptions.map((option) => (
          <div
            key={option.id}
            style={getOptionStyle(option.id)}
            onClick={() => handleOptionSelect(option.id)}
          >
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <div style={{
                width: '30px',
                height: '30px',
                borderRadius: '50%',
                border: '2px solid #667eea',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                marginRight: '15px',
                fontWeight: 'bold',
                color: selectedOption === option.id ? 'white' : '#667eea',
                backgroundColor: selectedOption === option.id ? '#667eea' : 'transparent'
              }}>
                {option.id}
              </div>
              <span style={{ fontSize: '16px' }}>{option.text}</span>
            </div>
          </div>
        ))}
      </div>

      <div style={{ textAlign: 'center', margin: '20px 0' }}>
        {message && (
          <div className={isCorrect ? 'correct' : 'incorrect'} style={{ padding: '10px', borderRadius: '5px' }}>
            {message}
          </div>
        )}
      </div>

      <div style={{ textAlign: 'center', margin: '20px 0' }}>
        {!isCorrect && (
          <button className="btn" onClick={checkAnswer} disabled={selectedOption === null}>
            提交答案
          </button>
        )}
        
        {isCorrect && (
          <button className="btn" onClick={() => setShowExplanation(!showExplanation)}>
            {showExplanation ? '隐藏解析' : '查看解析'}
          </button>
        )}
        
        {isCorrect && (
          <button className="btn" onClick={() => { resetQuestion(); onNext(); }}>
            下一题
          </button>
        )}
      </div>

      {showExplanation && (
        <div className="card" style={{ marginTop: '20px', backgroundColor: '#f8f9fa' }}>
          <h3>语法解析</h3>
          <p><strong>语法点：</strong>{question.explanation.grammar}</p>
          <p><strong>中文意思：</strong>{question.explanation.meaning}</p>
          <p><strong>语法规则：</strong>{question.explanation.rule}</p>
          <p><strong>例句：</strong>{question.explanation.example}</p>
          <p><strong>翻译：</strong>{question.explanation.translation}</p>
        </div>
      )}
    </div>
  );
};

export default GrammarQuestion; 